/*
 * Copyright (C) 2009 Show SMS open source project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bydavy.android.showsms.ui;

//~--- non-JDK imports --------------------------------------------------------

import android.content.Context;

import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;

import android.view.View;
import android.view.inputmethod.InputMethodManager;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewAnimator;

import com.bydavy.android.showsms.R;
import com.bydavy.android.showsms.model.Conversation;
import com.bydavy.android.showsms.model.Conversation.UpdateMessagesListener;
import com.bydavy.android.showsms.transaction.SmsMessageSender;
import com.bydavy.android.showsms.util.AppLog;

//~--- classes ----------------------------------------------------------------

public class ConversationBottomView extends ViewAnimator implements UpdateMessagesListener {
    //~--- static fields ------------------------------------------------------

    private static final String LOG_TAG               = AppLog.LOG_TAG;
    private static final boolean DEBUG                = true;
    private static final int INDEX_VIEW_MESSAGE_COUNT = 0;
    private static final int INDEX_VIEW_REPLY         = 1;

    //~--- fields -------------------------------------------------------------

    private Button mSendB;
    private EditText mReplyET;
    private Conversation mConversation;
    private TextView mMessageCount;
    private Thread uiThread;
    private int mCurrentMessageIndex;
    private Handler mHandler= new Handler();

    //~--- constructors -------------------------------------------------------

    public ConversationBottomView(Context context) {
        super(context);
    }

    public ConversationBottomView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    //~--- get methods --------------------------------------------------------

    public boolean isDisplayedReply() {
        return (getDisplayedChild() == INDEX_VIEW_REPLY);
    }

    public boolean isDisplayedMessageCount() {
        return (getDisplayedChild() == INDEX_VIEW_MESSAGE_COUNT);

    }

    //~--- set methods --------------------------------------------------------

    public void setVisibleMessage(int index) {
        mCurrentMessageIndex = index;
        updateView();
    }

    //~--- methods ------------------------------------------------------------

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        uiThread      = Thread.currentThread();

        mReplyET      = (EditText) findViewById(R.id.PreviewMsgToSend);
        mSendB        = (Button) findViewById(R.id.PreviewSendButton);
        mMessageCount = (TextView) findViewById(R.id.PreviewThreadMsgCount);
        mSendB.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        String text    = mReplyET.getText().toString();
                        String[] dests = new String[1];

                        dests[0] = mConversation.getContact().getPhoneNumber();

                        long threadId              = mConversation.getThreadId();
                        SmsMessageSender smsSender = new SmsMessageSender(getContext(), dests, text, threadId);
                        boolean sent               = smsSender.sendMessage();

                        if (DEBUG) {
                            Log.v(LOG_TAG, "Message envoye ? : " + sent);
                        }
                    }
                }.start();
            }
        });
    }

    public void bind(Conversation conversation) {
        mConversation = conversation;
        mConversation.addListenerMessages(this);
        updateView();
    }

    public void unbind() {
        mConversation.removeListenerMessages(this);
    }

    @Override
    public void showNext() {
        super.showNext();

        if (getDisplayedChild() == INDEX_VIEW_REPLY) {
            Context c              = getContext();
            InputMethodManager imm = (InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE);

            imm.hideSoftInputFromWindow(mReplyET.getWindowToken(), 0);
        }
    }

    @Override
    public void showPrevious() {
        super.showNext();

        if (getDisplayedChild() == INDEX_VIEW_REPLY) {
            Context c              = getContext();
            InputMethodManager imm = (InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE);

            imm.hideSoftInputFromWindow(mReplyET.getWindowToken(), 0);
        }
    }

    private void updateView() {
        int count   = mConversation.getMessageCount();
        int current = mCurrentMessageIndex + 1;

        mMessageCount.setText(current + "/" + count);
    }

    @Override
    public void onAddedMessages(int count, AddType type) {
        if (uiThread == Thread.currentThread()) {
            updateView();
        } else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    updateView();
                }
            });
        }
    }
}
